package fr.umlv.m2.jee.spij.service.unit;

import fr.umlv.m2.jee.spij.persistence.education.Unit;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * Display an unit. DTO pattern.
 *
 * @author thomas magny
 */
@Component("unitBean")
public class DisplayUnit implements Serializable {

    /**
     * unit primary key that is never displayed,
     * use to retrieve the unit in database.
     */
    private long id;

    /**
     * the name to display.
     */
    private String name;

    /**
     * the credit to display.
     */
    private int credit;

    /**
     * Empty constructor.
     */
    public DisplayUnit() {
    }

    /**
     * Constructs a DTO unit from unit.
     *
     * @param unit the unit that is displayed.
     */
    public DisplayUnit(final Unit unit) {
        if (unit != null) {
            storeData(unit);
        }
    }

    /**
     * @return the id.
     */
    public final long getId() {
        return id;
    }

    /**
     * @param newId the id to set.
     */
    public final void setId(final long newId) {
        this.id = newId;
    }

    /**
     * @return the name.
     */
    public final String getName() {
        return name;
    }

    /**
     * @param newName the name to set.
     */
    public final void setName(final String newName) {
        this.name = newName;
    }

    /**
     * @return the number of credit.
     */
    public final int getCredit() {
        return credit;
    }

    /**
     * @param newCredit the credit to set.
     */
    public final void setCredit(final int newCredit) {
        this.credit = newCredit;
    }

    /**
     * Stores datas from unit into DisplayUnit.
     *
     * @param unit the unit that is displayed.
     */
    private void storeData(final Unit unit) {
        if (unit.getId() != 0L) {
            setId(unit.getId());
        }
        if (unit.getCredit() != 0) {
            setCredit(unit.getCredit());
        }
        if (!unit.getName().isEmpty()) {
            setName(unit.getName());
        }
    }

    /**
     * @return the name of the unit.
     */
    @Override
    public final String toString() {
        return name;
    }
}
